package nz.ac.massey.jbuif.io;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Collection;


/**
 * Class XMLDataStoreAdapter implementing IDataStoreAdapter iinterface
 * @author AMIR H KIOUMARS
 *
 */
public class XMLDataStoreAdapter implements IDataStoreAdapter {

	
	/**
	 * load the bean objects (Deserialize an object)
	 * @param file the file name
	 * @return the collection of beans
	 */
	@SuppressWarnings("unchecked")
	@Override
	public Collection<Object> loadObjects(File file) {
		Collection<Object> objCollection = null;
		
		// Deserialize an object
		try {
		    XMLDecoder decoder = new XMLDecoder(new BufferedInputStream(
		        new FileInputStream(file)));
		    
		    objCollection = (Collection<Object>)decoder.readObject();
		    decoder.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
 
		return objCollection;
	}

	
	/**
	 * Implementing the save the object method (Serialize object into XML)
	 * @param file file name
	 * @param objCollection a collection of bean objects to save
	 */
	@Override
	public void saveObjects(File file, Collection<Object> objCollection) {
		try { 
			// Serialize object into XML
			XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(
					new FileOutputStream(file)));
			encoder.writeObject(objCollection);
			encoder.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
}
